package com.lhyl.front.web.lottery.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lhyl.front.common.DateUtils;
import com.lhyl.front.common.SiteUtil;
import com.lhyl.front.common.StringUtils;
import com.lhyl.front.constant.FrontConstant;
import com.lhyl.front.exception.FrontException;
import com.lhyl.front.exception.LotteryBetsException;
import com.lhyl.front.exception.SystemDBException;
import com.lhyl.front.web.controller.BaseController;
import com.lhyl.front.web.lottery.model.LotteryBets;
import com.lhyl.front.web.lottery.service.LotteryBetService;
import com.lhyl.front.web.shiro.model.User;

/**
 * 游戏记录
 * 
 * @author GusonYang
 * 
 */
@Controller
public class LotteryController extends BaseController {

	@Autowired
	public LotteryBetService lotteryBetService;

	private Map getLottery(String hash) throws Exception {
		Map map = new HashMap<String, Object>();
		map.put("hash", hash);
		List<Map> list = reportService.getReportResult("getLotteryByHash", map);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	private Map getCurrentLottery(Integer lotteryId) throws Exception {
		Date date = new Date();
		Map map = new HashMap<String, Object>();
		map.put("lottery_id", lotteryId);
		map.put("lottery_time", DateUtils.getTimeString(date));
		List<Map> list = reportService
				.getReportResult("getCurrentLottery", map);
		if (list != null && list.size() > 0) {
			Map currentLottery = list.get(0);
			currentLottery.put("lottery_date", DateUtils.getDateString(date));
			currentLottery.put("curr_time",
					((Timestamp) currentLottery.get("curr_time")).getTime());
			return currentLottery;
		}
		return null;
	}

	private List<Map> getPlayGroup(String type) throws Exception {
		Map map = new HashMap<String, Object>();
		map.put("type", type);
		List<Map> list = reportService.getReportResult("getPlayGroupByType",
				map);
		return list;
	}

	private List<Map> getPlay(Integer groupId) throws Exception {
		Map map = new HashMap<String, Object>();
		map.put("groupId", groupId);
		List<Map> list = reportService.getReportResult("getPlayByGroupId", map);
		return list;
	}

	/**
	 * 彩票页面 {type} 彩种 {ssc: 时时彩, x11x5: 十一选五, pk10: PK10} {name} 名字 {ssc:
	 * [chongqing: 重庆时时彩]}
	 */
	@RequestMapping(value = "/lottery/{type}/{name}", method = RequestMethod.GET)
	public String SSC(@PathVariable("type") String type,
			@PathVariable("name") String name, ModelMap modelMap)
			throws Exception {
		super.initBaseData(modelMap);
		Map lottery = getLottery(type + "/" + name);
		if (null != lottery) {
			List<Map> playGroups = getPlayGroup((String) lottery
					.get("lottery_type"));
			modelMap.put("type", type);
			modelMap.put("lottery", lottery);
			modelMap.put("playGroups", playGroups);
			Map currentLottery = getCurrentLottery((Integer) lottery.get("id"));
			modelMap.put("currentLottery", currentLottery);
			modelMap.put("user_fandian", this.getLoginUserObject().getFandian());
			return "lottery/" + type;
		}
		return "";
	}

	@RequestMapping(value = "/content/lottery/{type}/{name}", method = RequestMethod.GET)
	public String ContentLottery(@PathVariable("type") String type,
			@PathVariable("name") String name, ModelMap modelMap)
			throws Exception {
		Map lottery = getLottery(type + "/" + name);
		if (null != lottery) {
			List<Map> playGroups = getPlayGroup((String) lottery
					.get("lottery_type"));
			modelMap.put("type", type);
			modelMap.put("lottery", lottery);
			modelMap.put("playGroups", playGroups);
			Map currentLottery = getCurrentLottery((Integer) lottery.get("id"));
			modelMap.put("currentLottery", currentLottery);
			modelMap.put("user_fandian", this.getLoginUserObject().getFandian());
			return "lottery/content-" + type;
		}
		return "";
	}

	/**
	 * 根据玩法组获取该玩法组下的所有玩法
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/play", method = RequestMethod.GET)
	public void getPlays(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		String groupId = req.getParameter("groupId");
		if ("" == groupId) {
			errInfo.put("retcode", FrontConstant.INVALID_FORMAT_ERR[0]);
			errInfo.put("retmsg", FrontConstant.INVALID_FORMAT_ERR[1]);
			this.renderJson(resp, new Gson().toJson(errInfo));
			return;
		}

		Integer groupId_int = StringUtils.str2Int(groupId);
		// 是非数字类型，返回假
		if (0 == groupId_int) {
			errInfo.put("retcode", FrontConstant.INVALID_FORMAT_ERR[0]);
			errInfo.put("retmsg", FrontConstant.INVALID_FORMAT_ERR[1]);
			this.renderJson(resp, new Gson().toJson(errInfo));
			return;
		}
		List<Map> playList = this.getPlay(groupId_int);
		errInfo.put("retcode", 0);
		errInfo.put("data", playList);
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	/**
	 * 获取到当前彩票时间
	 */
	@RequestMapping(value = "/lottery/currenttime", method = RequestMethod.GET)
	public void getCurrentLotteryTime(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		String lotteryId = req.getParameter("lotteryId");
		if ("" == lotteryId) {
			errInfo.put("retcode", FrontConstant.INVALID_FORMAT_ERR[0]);
			errInfo.put("retmsg", FrontConstant.INVALID_FORMAT_ERR[1]);
			this.renderJson(resp, new Gson().toJson(errInfo));
			return;
		}
		Integer lotteryId_int = StringUtils.str2Int(lotteryId);
		// 是非数字类型，返回错误
		if (0 == lotteryId_int) {
			errInfo.put("retcode", FrontConstant.INVALID_FORMAT_ERR[0]);
			errInfo.put("retmsg", FrontConstant.INVALID_FORMAT_ERR[1]);
			this.renderJson(resp, new Gson().toJson(errInfo));
			return;
		}

		Map currentLottery = getCurrentLottery(lotteryId_int);
		// 添加间隔时间
		// long lotteryInterval =
		// StringUtils.str2Long(currentLottery.get("lotteryInterval")+"");
		// currentLottery.put("curr_time", new
		// Date().getTime()+lotteryInterval*1000);
		errInfo.put("retcode", 0);
		errInfo.put("data", currentLottery);
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	@RequestMapping(value = "/lottery/submit", method = RequestMethod.POST, headers = { "Content-type=application/json" })
	public void submit(HttpServletRequest req, HttpServletResponse resp,
			@RequestBody List<LotteryBets> lotteryBets) throws IOException {
		User user = super.getLoginUserObject();
		Map<String, Object> errInfo = new HashMap<String, Object>();
		if (lotteryBets != null) {
			Date betDate = new Date();
			String betsAddr = SiteUtil.getIpAddr(req);
			for (int i = 0; i < lotteryBets.size(); i++) {
				LotteryBets bet = lotteryBets.get(i);
				bet.setBetsIsdelete(FrontConstant.LOTTERY_BETS_NORMAL);
				bet.setUid(user.getUid());
				bet.setUname(user.getLoginName());
				bet.setBetsTime(betDate);
				bet.setBetsAddr(betsAddr);
			}
			try {
				lotteryBetService.saveLotteryBets(lotteryBets);
				errInfo.put("retcode", 0);
			} catch (LotteryBetsException e) {
				errInfo.put("retcode",  e.getMessage());
			} catch (Exception e) {
				errInfo.put("retcode",  e.getMessage());
			}
		}
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	@RequestMapping(value = "/lottery_bets/detail", method = RequestMethod.GET)
	public @ResponseBody
	Map rechargeSubmit(HttpServletRequest req, HttpServletResponse resp, ModelMap modelMap) throws Exception {
		List<Map> list = reportService.getReportResult("getLotteryBetDetail", this.buildQueryMap(req));
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 获取最近的彩票记录
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/history", method = RequestMethod.GET)
	public void getHistory(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		User user = super.getLoginUserObject();

		Map<String, Object> errInfo = new HashMap<String, Object>();
		Map map = new HashMap<String, Object>();
		map.put("user_id", user.getUid());
		List<Map> list = reportService
				.getReportResult("getLotteryHistory", map);

		errInfo.put("retcode", 0);
		errInfo.put("data", list);
		this.renderJson(resp, new GsonBuilder().setDateFormat("HH:mm:ss")
				.create().toJson(errInfo));
	}

	/**
	 * 判断当前时间是否在开奖间隔时间之内
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/distance", method = RequestMethod.GET)
	public void isCurrentLotteryTimeDistance(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		Map map = new HashMap<String, Object>();
		String lotteryId = req.getParameter("lotteryId");
		map.put("lottery_id", lotteryId);
		List<Map> list = reportService.getReportResult(
				"isCurrentLotteryTimeDistance", map);
		errInfo.put("retcode", 0);
		errInfo.put("data", list);
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	/**
	 * 是否开奖，未开奖是0 已开奖是开奖数据
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/opendata", method = RequestMethod.GET)
	public void queryLotteryOpenDataInfo(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		Map map = new HashMap<String, Object>();
		String lotteryId = req.getParameter("lotteryId");
		map.put("lottery_id", lotteryId);
		List lotteryData = reportService.getReportResult(
				"queryLotteryOpenDataInfo", map);
		if (lotteryData == null || lotteryData.isEmpty()) {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("lottery_data", "-,-,-,-,-");
			errInfo.put("retcode", 0);
			errInfo.put("data", result);
		} else {
			errInfo.put("retcode", 0);
			errInfo.put("data", lotteryData.get(0));
		}
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	/**
	 * 追号查询
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/appendbet", method = RequestMethod.GET)
	public void queryAppendBet(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		String lotteryId = req.getParameter("lotteryId");
		String lotteryNo = req.getParameter("lotteryNo");
		Map map = new HashMap<String, Object>();
		map.put("lotteryId", lotteryId);
		map.put("lotteryNo", lotteryNo);
		List<Map> list = reportService.getReportResult("queryAppendBet", map);
		errInfo.put("retcode", 0);
		errInfo.put("data", list);
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	/**
	 * @desc 撤单
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "/lottery/cancelLotteryBets", method = RequestMethod.GET)
	public void cancelLotteryBets(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		String lotteryBetsId = req.getParameter("lotteryBetsId");// 校验是否超过撤单时间
		try {
			this.reportService.verification("verificationCancelBet", this.buildQueryMap(req));
			this.lotteryBetService.cancelLotteryBets(StringUtils
					.str2Int(lotteryBetsId));
			errInfo.put("retcode", 0);
		} 
		catch (FrontException e) {
			errInfo.put("retcode", e.getErrorCode());
			errInfo.put("retmsg", e.getMessage());
		} 
		catch (Exception e) {
			errInfo.put("retcode", "-1");
			errInfo.put("retmsg", e.getMessage());
		}
		this.renderJson(resp, new Gson().toJson(errInfo));
	}

	/**
	 * 查询少量彩种
	 * 
	 * @throws SystemDBException
	 * @throws IOException
	 */
	@RequestMapping(value = "/lottery/queryLittleLottery", method = RequestMethod.GET)
	public void queryLittleLottery(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> errInfo = new HashMap<String, Object>();
		try {
			List<Map> list = reportService.getReportResult(
					"queryHomePageLotteryData", new HashMap<String, Object>());
			errInfo.put("retcode", 0);
			errInfo.put("retmsg", "ok");
			errInfo.put("data", list);
		} catch (Exception e) {
			errInfo.put("retcode", -1);
			errInfo.put("retmsg", e.getMessage());
		}
		this.renderJson(resp, new Gson().toJson(errInfo));
	}
	
	
	/** 
	 * 查询历史开奖数据
	 * @throws SystemDBException
	 * @throws IOException
	 */
	@RequestMapping(value = "/lottery/queryHistoryLotteryData", method = RequestMethod.GET)
	public void queryHistoryLotteryData(HttpServletRequest req, HttpServletResponse resp) throws Exception 
	{
		Map<String, Object> param = this.buildQueryMap(req);
		this.renderMsg(resp, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, 
				this.reportService.getReportResult("queryHistoryLotteryData", param));
	}
}
